package com.teach.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import com.teach.config.Config;
import com.teach.service.SmsMessageService;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;

@Service
@Primary
public class SmsMessageServiceBySmsChinese implements SmsMessageService {

	private final static Logger log = LoggerFactory.getLogger(SmsMessageServiceBySmsChinese.class);

	@Autowired
	private Config config;

	private TimedCache<String, String> cache;

	private Map<Integer, String> exceptionMessage = new HashMap<>();

	@PostConstruct
	public void init() {
		cache = CacheUtil.newTimedCache(config.smsCacheDefaultTime);
		log.info("创建了短信缓存对象");
		exceptionMessage.put(-1, "没有该用户账户");
		exceptionMessage.put(-2, "接口密钥不正确");
		exceptionMessage.put(-21, "MD5接口密钥加密不正确");
		exceptionMessage.put(-3, "短信数量不足");
		exceptionMessage.put(-11, "该用户被禁用");
		exceptionMessage.put(-14, "短信内容出现非法字符");
		exceptionMessage.put(-4, "手机号格式不正确");
		exceptionMessage.put(-41, "手机号码为空");
		exceptionMessage.put(-42, "短信内容为空");
		exceptionMessage.put(-51, "短信签名格式不正确");
		exceptionMessage.put(-52, "短信签名太长");
		exceptionMessage.put(-6, "IP限制");
	}

	@Override
	public void send(String tel) {
		send(tel, config.smsCacheDefaultTime);
	}

	@Override
	public void send(String tel, long timeout) {
		if (cache.get(tel) != null) {
			throw new RuntimeException("请不要重复发生验证码！");
		}
		String code = RandomUtil.randomNumbers(6);
		Map<String, Object> formMap = new HashMap<>();
		formMap.put("Uid", config.smsChinese.uid);
		formMap.put("Key", config.smsChinese.key);
		formMap.put("smsMob", tel);
		formMap.put("smsText", String.format(config.smsChinese.message, code));

		HttpResponse response = new HttpRequest(config.smsChinese.api).setMethod(Method.POST)
				.headerMap(config.smsChinese.headers, true).form(formMap).execute();
		if (response.getStatus() != 200) {
			throw new RuntimeException("访问短信发生接口失败");
		} else {
			int ret = Integer.valueOf(response.charset("utf-8").body());
			String msg = null;
			if(ret<=0) {
				msg = exceptionMessage.get(ret);
				if(msg==null) {
					msg="发生短信失败！";
				}
				throw new RuntimeException(msg);
			}
			log.info("成功发生短信验证码：tel:{},code:{}",tel,code);
		}
	}

	@Override
	public boolean check(String tel, String code) {
		if(StrUtil.hasBlank(code)) {
			return false;
		}
		return code.equalsIgnoreCase(cache.get(tel));
	}

}
